package com.akl.ssmspringboot.controller.log;

import com.akl.ssmspringboot.entity.LoginLog;
import com.akl.ssmspringboot.service.LoginLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.util.Date;

/**
 * 登录日志 切面实现
 */
@Aspect
@Component
public class LoginLogAop {

    @Autowired
    private LoginLogService loginLogService;

    /**
     * 管理员登录方法的切入点
     */
    @Pointcut("execution(* com.akl.ssmspringboot.controller.LoginController.login(..))")
    public void loginCell() {
    }

    /**
     * 登录操作(后置通知)
     * @param joinPoint
     * @throws Throwable
     */
    @AfterReturning(value = "loginCell()", argNames = "joinPoint")
    public void loginLogAop(JoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().getName();
        // 没有参数
        if (joinPoint.getArgs() == null) {
            return;
        }
        if (methodName != null && "login".equals(methodName)) {
            LoginLog loginLog = new LoginLog();
            loginLog.setUserId(5);
            String loginUserIp = InetAddress.getLocalHost().getHostAddress();
            loginLog.setLoginUserIp(loginUserIp);
            loginLog.setLoginTime(new Date());
            loginLog.setLoginDesc("登陆:" + opContent(joinPoint));
            loginLogService.insert(loginLog);
        }

    }

    /**
     * 获取执行的操作的信息
     * @param joinPoint
     * @return
     */
    public String opContent(JoinPoint joinPoint) {
        //获取类名
        String className = joinPoint.getTarget().getClass().getName();
        //获取方法名
        String methodName = joinPoint.getSignature().getName();
        String str = "执行了" + className + "类的" + methodName + "方法";
        return str;
    }

}